package com.jgraves.WikiToSpeech;
/*
 * Copyright (C) 2011 John Graves
 */

import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

// TODO Have alternative (faster) pull of JSON scripts into faster Java structure
// TODO Fade in text animations
// TODO h for help (both command and menu)
// TODO on-line documentation
// TODO Sort out way for playback language to be specified across Mac/Android

/**
 * Parses files or URLs into scripts which play using text-to-speech 
 * @author johngraves
 */
public class WikiToSpeech extends Activity implements TextToSpeech.OnInitListener {

	// Identifiers for menu items
	private static final int HISTORY_MENU_ID = Menu.FIRST;
	private static final int SETTINGS_MENU_ID = Menu.FIRST+1;
	private static final int EXIT_MENU_ID = Menu.FIRST+2;
	private static final int CONTENTS_MENU_ID = Menu.FIRST+3;
	private static final int INPUT_MENU_ID = Menu.FIRST+4;
	private static final int BARCODE_MENU_ID = Menu.FIRST+5;
	private static final int OPEN_MENU_ID = Menu.FIRST+6;

	/** The file name or URL on the response side of an answer;[destination]response 
	 * or provided by an open command
	 * */

	/** Data source for sequence */
	public static TextToSpeech mTts;

	// Layouts
	private Button mTextToSpeechButton;
	private Button mWikiToSpeechButton;
	private Button mEtherpadToSpeechButton;
	private Button mQRCodeToSpeechButton;
	private Button mNFCToSpeechButton;
	private Button mZIPToSpeechButton;
	private LinearLayout mInitializingLinearLayout;

	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		intent = new Intent("com.google.zxing.client.android.SCAN");

		//        // Load preferences
		//        addPreferencesFromResource(R.xml.preferences);

		setContentView(R.layout.home);
		//		setTTSLanguage(Locale.UK);

		//		mTts.setLanguage(Locale.UK);
		//		print("UK available: " + mTts.isLanguageAvailable(Locale.UK));


		mTextToSpeechButton = (Button) findViewById(R.id.text_to_speech_button);
		mWikiToSpeechButton = (Button) findViewById(R.id.wiki_to_speech_button);
		mEtherpadToSpeechButton = (Button) findViewById(R.id.etherpad_to_speech_button);
		mQRCodeToSpeechButton = (Button) findViewById(R.id.qr_code_to_speech_button);
		mNFCToSpeechButton = (Button) findViewById(R.id.nfc_to_speech_button);
		mZIPToSpeechButton = (Button) findViewById(R.id.zip_to_speech_button);
		mInitializingLinearLayout = (LinearLayout) findViewById(R.id.initializing_linearlayout);

		// Restore preferences
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		State.setLanguage(prefs.getString("language", "UK"));
		initializeTts();
		//		// Greet the user.
		//		//		myList = readFileFromLocal(this);
		//		//		final String siteUrl = "http://code.google.com/p/open-allure-ds/wiki/Music";
		//		//final String siteUrl = "http://localhost:8000/music.html";
		//		//final String siteUrl = "http://127.0.0.1:8000/music.html";
		//		instream = WikiToSpeech.this.getResources().openRawResource(R.raw.chatterboxchallenge2011script);
		//		// TODO				final String siteUrl = "http://openallure.wikia.com/wiki/Category:Open_Allure_Script";
		//		// TODO				final String siteUrl = "http://openallureds.ning.com/profiles/blogs/music-1";
		//		ReadURL.readURL(this, instream, Constants.TXT);
		//
		//		State.setOnQuestion(0);
		//
		//		mTTSLinearLayout.setOnLongClickListener(new OnLongClickListener() {
		//
		//			public boolean onLongClick(View v) {
		//				mInputEditText.setVisibility(View.VISIBLE);
		//				return true;
		//			}
		//		});

		mTextToSpeechButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClassName("com.jgraves.WikiToSpeech", "com.jgraves.WikiToSpeech.FileChooser");
				intent.putExtra("suffix", ".txt");
				startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
			}
		});
		mWikiToSpeechButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(WikiToSpeech.this, InputView.class);
				//				i.putExtra(Constants.EXTRA_INPUT_STRING, "http://dl.dropbox.com/u/12838403/Vodafone/Vodafone.txt");
				i.putExtra(Constants.EXTRA_INPUT_STRING, "http://aucklandunitarian.pagekite.me/MensGroup");
				i.putExtra(Constants.EXTRA_INPUT_TYPE, Constants.HTML);
				startActivity(i);
			}
		});
		mEtherpadToSpeechButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(WikiToSpeech.this, InputView.class);
				i.putExtra(Constants.EXTRA_INPUT_STRING, "http://ietherpad.com/");
				i.putExtra(Constants.EXTRA_INPUT_TYPE, Constants.HTML_ETHERPAD);
				startActivity(i);
			}
		});
		mQRCodeToSpeechButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				intent.setPackage("com.google.zxing.client.android");
				intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				startActivityForResult(intent, Constants.REQUEST_CODE_SCAN); // request code must be 0
			}
		});
		mNFCToSpeechButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				startActivity(new Intent(WikiToSpeech.this,ReadNFC.class));
			}
		});
		mZIPToSpeechButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClassName("com.jgraves.WikiToSpeech", "com.jgraves.WikiToSpeech.FileChooser");
				intent.putExtra(Constants.EXTRA_INPUT_TYPE,Constants.ZIP);
				startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
			}
		});

	} // end onCreate

	static void setTTSLanguage(Locale loc) {
		if (null!=mTts) {
			mTts.setLanguage(loc);
		}
	}

	// ---------------------------
	public void initializeTts() {
		// Initialize text-to-speech. This is an asynchronous operation.
		// The OnInitListener (second argument) is called after initialization completes.
		if (null==mTts) {
			mTts = new TextToSpeech(this, this);
		}
	}

	// Implements TextToSpeech.OnInitListener.
	public void onInit(int status) {
		// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
		if (status == TextToSpeech.SUCCESS) {
			mInitializingLinearLayout.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onResume(){		
		super.onResume();
		mTts.stop();

	} // end onResume

	@Override
	protected void onStop(){
		super.onStop();

		Library.savePreferences(this);
	} // end onStop



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, HISTORY_MENU_ID, 0, R.string.history)
		.setIcon(android.R.drawable.ic_menu_preferences);
		menu.add(0, EXIT_MENU_ID, 0, R.string.exit)
		.setIcon(android.R.drawable.ic_menu_revert);
		menu.add(0, INPUT_MENU_ID, 0, R.string.input)
		.setIcon(android.R.drawable.ic_menu_edit);
		menu.add(0, CONTENTS_MENU_ID, 0, R.string.contents)
		.setIcon(android.R.drawable.ic_menu_search);
		menu.add(0, SETTINGS_MENU_ID, 0, R.string.settings)
		.setIcon(android.R.drawable.ic_menu_preferences);
		menu.add(0, BARCODE_MENU_ID, 0, R.string.scan)
		.setIcon(android.R.drawable.ic_menu_preferences);
		menu.add(0, OPEN_MENU_ID, 0, R.string.open)
		.setIcon(android.R.drawable.ic_menu_save);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle all of the possible menu actions.
		switch (item.getItemId()) {
		case HISTORY_MENU_ID:
			Intent historyIntent = new Intent(WikiToSpeech.this, HistoryView.class);
			startActivityForResult(historyIntent, Constants.REQUEST_CODE_PICK_FROM_HISTORY);
			break;
		case OPEN_MENU_ID:
			openFileDialog();
			break;
		case SETTINGS_MENU_ID:
			Intent launchPreferencesIntent = new Intent().setClass(this, Preferences.class);
			startActivityForResult(launchPreferencesIntent, Constants.REQUEST_CODE_PREFERENCES);
			break;
		case EXIT_MENU_ID:
			String zipFile = Environment.getExternalStorageDirectory() + "/easier_way.zip"; 
			String unzipLocation = Environment.getExternalStorageDirectory() + "/WikiToSpeech/"; 

			Decompress d = new Decompress(zipFile, unzipLocation); 
			d.unzip(); 
			finish();
			break;
		case INPUT_MENU_ID:
			Intent i = new Intent(WikiToSpeech.this, InputView.class);
			startActivity(i);
			break;
		case BARCODE_MENU_ID:
			intent.setPackage("com.google.zxing.client.android");
			intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
			startActivityForResult(intent, 0);

			break;
		}
		return super.onOptionsItemSelected(item);
	}


	/**
	 * Opens the file manager to select a file to open.
	 */
	private void openFileDialog() {

	}



	@Override
	public void onDestroy() {
		// Don't forget to shutdown!
		if (mTts != null) {
			mTts.stop();
			mTts.shutdown();
			mTts = null;
		}

		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		Intent i = new Intent(WikiToSpeech.this, QuestionView.class);
		
		switch (requestCode) {
		case Constants.REQUEST_CODE_SCAN:
			if (resultCode == RESULT_OK) {
				String contents = data.getStringExtra("SCAN_RESULT");
				// Handle successful scan
				i.putExtra(Constants.EXTRA_INPUT_STRING, contents);
				i.putExtra(Constants.EXTRA_INPUT_TYPE, State.getDestinationType(contents));
				startActivity(i);
			} else if (resultCode == RESULT_CANCELED) {
				// Handle cancel
			}
			break;

		case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
			if(resultCode == RESULT_OK) {
				// Go to Question View with extras
				i.putExtra(Constants.EXTRA_INPUT_STRING, data.getStringExtra(Constants.EXTRA_FILENAME));
				i.putExtra(Constants.EXTRA_INPUT_TYPE, State.getDestinationType(data.getStringExtra(Constants.EXTRA_FILENAME)));
				startActivity(i);
			}
			break;

		case Constants.REQUEST_CODE_PICK_FROM_HISTORY:
			// Go to Question View with extras
			i.putExtra(Constants.EXTRA_INPUT_STRING, data.getStringExtra(Constants.EXTRA_FILENAME));
			i.putExtra(Constants.EXTRA_INPUT_TYPE, State.getDestinationType(data.getStringExtra(Constants.EXTRA_FILENAME)));
			startActivity(i);
			break;
		}
		return;
	}

	// -----------------------
	public static void print(Object obj){
		System.out.println(obj.toString());
	}
} // end of TextToSpeechActivity